from django.db.models import Q
from rest_framework.viewsets import GenericViewSet
from projects.base.mixin import (CreateModelMixin, ListModelMixin,
                                 RetrieveModelMixin, DestroyModelMixin)
from projects.base.pagenations import DefaultPagination
from .serializers import MessageSerializer
from .validates import MessageValidate
from .models import Message


class MessageViewSet(GenericViewSet, CreateModelMixin, RetrieveModelMixin,
                     ListModelMixin, DestroyModelMixin):
    serializer_class_table = {
        "list": MessageSerializer,
        "retrieve": MessageSerializer,
        "destroy": MessageSerializer,
        "create": MessageValidate,
    }
    queryset = Message.objects
    pagination_class = DefaultPagination
    # TODO: 认证, 自定义认证规则
    # authentication_classes = []

    def get_serializer_class(self):
        return self.serializer_class_table.get(
            self.action, None
        )

    def get_queryset(self):
        from_user = self.request.query_params.get("from_user")
        to_user = self.request.query_params.get("to_user")
        queryset = Message.objects.filter(Q(from_user=from_user, to_user=to_user) |
                                          Q(from_user=to_user, to_user=from_user)).all()

        return queryset

